package com.alibaba.csp.sentinel.dashboard.rule.nacos.gatewayRule;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("gatewayNaocsProvider")
public class GatewayNaocsProvider implements DynamicRuleProvider<List<GatewayFlowRuleEntity>> {

    @Autowired
    private ConfigService configService;

    @Override
    public List<GatewayFlowRuleEntity> getRules(String appName, String ip, Integer port) throws Exception {
        String rules = configService.getConfig(appName + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }

        //将ParamFlowRule转成ParamFlowRuleEntity
        List<GatewayFlowRule> gatewayFlowRules = JSON.parseArray(rules, GatewayFlowRule.class);
        List<GatewayFlowRuleEntity> entities = gatewayFlowRules.stream().
                map(rule -> GatewayFlowRuleEntity
                .fromGatewayFlowRule(appName, ip, port, rule))
                .collect(Collectors.toList());
        return entities;
    }
}
